package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import common.AppConfig;
import common.AppResult;
import dao.UserDao;
import model.User;
import utills.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author quan
 * @Description 功能1：实现登录功能
 * @Date 2023/6/30 17:05
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    //创建一个UserDao
    private UserDao userDao = new UserDao();
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、设置编码集
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");
        //2、获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //3、非空校验
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
//            resp.getWriter().write("{\"code\": 1000, \"message\" : \"用户名密码不能为空\"}");
            //上面一行替换为下面的方法
            AppResult appResult = AppResult.failed("用户名密码不能为空");
            resp.getWriter().write(objectMapper.writeValueAsString(appResult));
            return;
        }
        //4、说明用户名存在：获取从数据库读取到的用户，调用Dao
        User user = userDao.selectByUsername(username);
        //判断用户是否为空
        if(user == null){
//            resp.getWriter().write("{\"code\": 1000, \"message\" : \"用户名密码不正确\"}");
            //使用统一的数据返回格式
            AppResult appResult = AppResult.failed("用户名密码不正确");
            resp.getWriter().write(objectMapper.writeValueAsString(appResult));
            return;
        }
        //判断密码是否正确
        if(!user.getPassword().equals(password)){
//            resp.getWriter().write("{\"code\": 1000, \"message\" : \"用户名密码不正确\"}");
            AppResult appResult = AppResult.failed("用户名密码不正确");
            resp.getWriter().write(objectMapper.writeValueAsString(appResult));
            return;
        }
        //5、说明用户名和密码都正确，将用户信息保存在Session中
        HttpSession session = req.getSession(true);//true表示如果是第一次则要设置一个session
        //设置session属性:使用全局定义的key
        session.setAttribute(AppConfig.USER_SESSION_KEY,user);
        //返回结果
        //code: 0表示成功,1000表示失败
//        resp.getWriter().write("{\"code\": 0, \"message\" : \"登录成功\"}");
        AppResult appResult = AppResult.success("登录成功");
        resp.getWriter().write(objectMapper.writeValueAsString(appResult));
        //打印日志
        System.out.println("登录成功 : " + user.getId());
    }
}
